package com.marveal.rabbit.producer.config.database;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;

@Import(value = {RabbitProducerDataSourceProperties.class})
public class DataSourceSelector {

    private RabbitProducerDataSourceProperties properties;

    public DataSourceSelector(RabbitProducerDataSourceProperties rabbitProducerDataSourceProperties) {
        this.properties = rabbitProducerDataSourceProperties;
    }

    public HikariDataSource getHikariDataSource(DataSource rabbitProducerDataSource) {
        HikariDataSource hikariDataSource = (HikariDataSource) rabbitProducerDataSource;
        hikariDataSource.setPoolName(properties.getPoolName());
        hikariDataSource.setMinimumIdle(properties.getMinimumIdle());
        hikariDataSource.setConnectionTimeout(properties.getConnectionTimeout());
        hikariDataSource.setIdleTimeout(properties.getIdleTimeout());
        hikariDataSource.setMaxLifetime(properties.getMaxLifetime());
        hikariDataSource.setAutoCommit(properties.isAutoCommit());
        hikariDataSource.setConnectionTestQuery(properties.getConnectionTestQuery());
        return hikariDataSource;
    }

    @Bean
    public DataSourceSelector dataSourceSelector(RabbitProducerDataSourceProperties properties) {
        return new DataSourceSelector(properties);
    }
}
